package com.hbnu.tools;

import static com.hbnu.web.Client.*;

public class PathTool {
    //修改tip
    public static void setTip(String name){
        tip.replace(startPath,endPath,name);
        endPath=startPath+name.length();
    }

    //使用String Builder计算相对地址，节省空间
    private static final StringBuilder cPath=new StringBuilder();
    public static String calcPath(String path, String word){
        //与当前路径一致 分割斜杠
        String[] split = word.split("/+");
        //println("(输入命令:"+word+"),(解析为: "+Arrays.toString(split)+"),(长度:"+split.length+")");
        //路径为 /
        if(split.length==0) {
            return "~";
        }
        //绝对路径
        int i=0;
        if(split[0].isEmpty()){
            cPath.replace(0,cPath.length(),"~");
            i=1;
        }
        //相对路径
        else cPath.replace(0,cPath.length(),path);

        for(;i<split.length;i++){
            if("..".equals(split[i])){
                getBuilderParentPath(cPath);
                continue;
            }
            if(".".equals(split[i])){
                continue;
            }
            cPath.append("/").append(split[i]);
        }
        return cPath.toString();
    }
    private static void getBuilderParentPath(StringBuilder path){
        int index = path.lastIndexOf("/");
        if(index==-1){
            //已经到root目录了，到根目录不处理
            return;
        }
        path.delete(index, path.length());
    }

    //获取父级地址
    public static String getParentPath(String path){
        int index = path.lastIndexOf("/");
        if(-1==index) return "~";
        return path.substring(0,index);
    }

    //通过地址获取名称
    public static String getPathName(String path) {
        return path.substring(path.lastIndexOf("/")+1);
    }
}
